package com.lap.service.starter.tools;

import org.apache.commons.lang3.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;

/**
 * URI 工具类
 *
 * @author Shuisheng.Lao
 * @version 0.0.1
 */
public final class UriUtil {
  private static final String SLASH = "/";
  private static final String REGEX = "\\{\\w+\\}";
  private static final String UNDER_LINE = "_";
  private static final String LINE = "-";
  private static final String PERIODS = ".";

  private UriUtil() {}

  /**
   *
   *
   * <pre>
   *  获取URI,
   *  例如:
   *  parentUri: "", [] 返回:""
   *  parentUri: "api",["test","a"] 返回 /api/test
   * </pre>
   *
   * @param parentUri 父uri
   * @param uriArray uri数组
   * @return 集合
   */
  public static String getUri(String parentUri, String[] uriArray) {
    String uri = getUriFromArray(uriArray);
    StringBuilder result = new StringBuilder(64);
    if (StringUtils.isNotBlank(parentUri)) {
      result.append(parentUri);
    }
    if (StringUtils.isNotBlank(uri)) {
      if (!uri.startsWith(SLASH)) result.append(SLASH);
      result.append(uri);
    }
    return result.toString();
  }

  /**
   * 通过uri数组获取 uri,仅仅获取第一个
   *
   * @param uriArray uri 数组
   * @return uri[0]o
   */
  private static String getUriFromArray(String[] uriArray) {
    return Stream.of(uriArray).filter(StringUtils::isNotBlank).findFirst().orElse(Constants.BLANK);
  }

  /**
   * 根据模块和uri获取编码
   *
   * @param clazz 类型
   * @return 返回uri
   */
  public static String getClassName(Class<?> clazz) {
    StringBuilder result = new StringBuilder(32);

    String packageName = clazz.getPackageName();
    if (StringUtils.isNotBlank(packageName)) {
      result.append(packageName).append(PERIODS);
    }

    String name = clazz.getSimpleName();
    if (StringUtils.isNotBlank(name)) {
      result.append(name);
    }
    return result.toString();
  }

  /**
   *
   *
   * <pre>
   * 获取uri_code
   * 例如:
   * module: test, uri: /api/user, method: get => test_get_api_user
   * </pre>
   *
   * @param module 模块
   * @param uri URI
   * @param method 方法
   * @return URI编码
   */
  public static String getUriCode(String module, String uri, String method) {
    StringBuilder sb = new StringBuilder(256);
    if (StringUtils.isNotBlank(module)) sb.append(module);

    if (StringUtils.isNotBlank(method)) sb.append(UNDER_LINE).append(method.toLowerCase());

    if (StringUtils.isNotBlank(uri)) {
      Pattern pattern = Pattern.compile(REGEX);
      Matcher matcher = pattern.matcher(uri);
      String newUri = matcher.replaceAll("id").replace(SLASH, UNDER_LINE).replace(LINE, UNDER_LINE);
      sb.append(UNDER_LINE).append(newUri);
    }
    return sb.toString();
  }
}
